package indexPack;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import net.htmlparser.jericho.CharacterReference;
import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.HTMLElementName;
import net.htmlparser.jericho.Source;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Field.Index;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.document.Field.TermVector;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.SimpleFSDirectory;
import org.apache.lucene.util.Version;


public class CustomizedIndex {

    private IndexWriter index;

    public CustomizedIndex(File indexDir, File dataDir, Analyzer analyzer) throws IOException {
        createIndex(indexDir, dataDir, analyzer);
    }

    private void createIndex(File indexDir, File dataDir, Analyzer analyzer) throws IOException {
        
        if (!dataDir.exists() || !dataDir.isDirectory()) {
            throw new IOException("\"" + dataDir + "\" no existe o no es un directorio.");
        }
        IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_33, analyzer);
        this.index = new IndexWriter(new SimpleFSDirectory(indexDir), config);
    }
    
    public IndexWriter getIndex(){
        return this.index;
    }

    // Esta funcion retorna un boolean para saber si el archivo se pudo indexar o no
    public boolean indexFile(File file) throws IOException {

        if (!file.isHidden() && file.exists() && file.canRead()) {
            Document document = new Document();
            Source fileSource = new Source(new FileReader(file));
            String fileBody = parseFileContent(fileSource);
            String fileTitle = getFileTitle(fileSource);
            String movieYear = "none";
            try {
                movieYear = fileTitle.substring(fileTitle.indexOf("(")+1, fileTitle.indexOf(")"));
            } catch (Exception ex) {
                System.out.println(ex);
            }
            if (fileBody != null && fileTitle != null) {
                document.add(new Field("contenido", fileBody, Store.YES, Index.ANALYZED, TermVector.WITH_POSITIONS_OFFSETS));
                document.add(new Field("direccion", file.getAbsolutePath(), Store.YES, Index.ANALYZED));
                document.add(new Field("titulo", fileTitle.replace("Review for", ""), Store.YES, Index.ANALYZED, TermVector.WITH_POSITIONS_OFFSETS));
                document.add(new Field("anio", movieYear, Store.YES, Index.ANALYZED, TermVector.WITH_POSITIONS_OFFSETS));
                // Finalmente agrego el archivo al indice.
                this.index.addDocument(document);
            }
            return true;    // Retorna verdadero cuando se indexo el archivo
        }
        return false;   // Retorna falso cuando el archivo es oculto, o no existe o no se puede leer
    }

    private String parseFileContent(Source source) {
        Element bodyElements = source.getFirstElement(HTMLElementName.BODY);
        if (bodyElements != null) {
            return bodyElements.getContent().getTextExtractor().setConvertNonBreakingSpaces(true).toString();
        }
        return null;
    }

    private String getFileTitle(Source source) {
        Element titleElement = source.getFirstElement(HTMLElementName.TITLE);
        if (titleElement != null) {
            return CharacterReference.decodeCollapseWhiteSpace(titleElement.getContent());
        }
        return null;
    }

    public void close() throws CorruptIndexException, IOException {
        this.index.close();
    }
    
    public void optimize() throws CorruptIndexException, IOException {
        this.index.optimize();
    }

}
